package util;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.security.core.GrantedAuthority;

import java.util.Collection;
import java.util.Date;

/**
 * Created by Administrator on 2018/4/11.
 */
@ConfigurationProperties(prefix = "jwt.config")
public class JwtUtil {

    // 密钥
    private String key ;

    // 过期时间，1小时
    private long ttl ;

    public String getKey() {
        return key;
    }

    public void setKey(String key) {
        this.key = key;
    }

    public long getTtl() {
        return ttl;
    }

    public void setTtl(long ttl) {
        this.ttl = ttl;
    }

    /**
     * 生成JWT
     * @Param id 用户id
     * @Param subject 用户名
     * @Param roles 用户角色
     */
    public String createJWT(String id, String subject, String roles) {
        long nowMillis = System.currentTimeMillis();
        Date now = new Date(nowMillis);
        JwtBuilder builder = Jwts.builder()
                // JWT的唯一标识，回避重放攻击
                .setId(id)
                // 代表JWT的主体，即它的所有人
                .setSubject(subject)
                // 签发时间
                .setIssuedAt(now)
                // 加密算法、密钥
                .signWith(SignatureAlgorithm.HS256, key)
                // 载荷
                .claim("roles", roles);
        if (ttl > 0) {
            // 设置过期时间
            builder.setExpiration( new Date( nowMillis + ttl));
        }
        return builder.compact();
    }

    /**
     * 重载token的创建方法，添加基地id，基地身份，店铺id信息
     * @param id
     * @param subject
     * @param authority
     * @return
     */
    public String createJWT(String id, String subject, String roles, Collection<GrantedAuthority> authority) {
        long nowMillis = System.currentTimeMillis();
        Date now = new Date(nowMillis);
        JwtBuilder builder = Jwts.builder()
                .setId(id)
                .setSubject(subject)
                .setIssuedAt(now)
                .signWith(SignatureAlgorithm.HS256, key)
                .claim("roles", roles)
                .claim("authorities", authority);
        if (ttl > 0) {
            builder.setExpiration( new Date( nowMillis + ttl));
        }
        return builder.compact();
    }

    /**
     * 解析JWT
     * @param jwtStr
     * @return
     */
    public Claims parseJWT(String jwtStr){
        return  Jwts.parser()
                .setSigningKey(key)
                .parseClaimsJws(jwtStr)
                .getBody();
    }

    /**
     * 刷新JWT
     * @param jwtStr
     * @return
     */
    public String updateJWT(String jwtStr){
        Claims claims = parseJWT(jwtStr);
        return claims.get("role").toString().equals("user")
                ?
                createJWT(claims.getId(),
                        claims.getSubject(),
                        claims.get("role").toString())
                :
                createJWT(claims.getId(),
                        claims.getSubject(),
                        claims.get("role").toString(),
                        (Collection<GrantedAuthority>)claims.get("authorities"));
    }
}

